import { defineStore } from 'pinia'
import { reqLogin } from '@/api/user/index'
import type { LoginForm } from '@/api/user/type.ts'
import { SET_TOKEN, GET_TOKEN } from '@/utils/token'

import routes from '@/router/routes'
import type { UseState } from '../type'

const useUserStore = defineStore('User', {
  // pinia仓库存储数据的地方
  state: (): UseState => {
    return {
      token: GET_TOKEN(),
      menuRoutes: routes
    }
  },

  // 异步|逻辑的地方
  actions: {
    // 用户登录的方法
    async userLogin(data: LoginForm) {
      const result = await reqLogin(data)
      console.log(result)

      if (result.code === 200) {
        // 使用pinia仓库存储token
        this.token = result.data.token
        // 再用本地缓存持久化存储token
        SET_TOKEN(result.data.token)
        return 'ok'
      }
      return Promise.reject(new Error(result.data.message))
    }
  },

  getters: {}
})

export default useUserStore
